//
//  UIButton+Countdown.m
//  BLUitility
//
//  Created by iBenz on 17/4/12.
//  Copyright © 2017年 Benzii. All rights reserved.
//

#import "UIButton+Countdown.h"
#import <objc/runtime.h>

@interface __UIButtonCountdownDelegate : NSObject
@property(nonatomic, weak) UIButton *button;
@property(nonatomic, weak) NSTimer *timer;
@property(nonatomic, copy) NSString *(^titleBlock)(int second);
@property(nonatomic, assign) int seconds;
@property(nonatomic, assign) BOOL enableWhenProcessing;
@property(nonatomic, assign) BOOL disableWhenFinished;
@end

@implementation __UIButtonCountdownDelegate

- (void)handlerTimer:(NSTimer *)timer {
    if (_seconds>=0) {
        self.button.enabled = _enableWhenProcessing;
        UIControlState state = self.button.state&UIControlStateDisabled?UIControlStateDisabled:UIControlStateNormal;
        [self.button setTitle:_titleBlock(_seconds) forState:state];
        self.seconds--;
    }
    else {
        self.button.enabled = !_disableWhenFinished;
        [_timer invalidate];
    }
}

@end

@interface UIButton ()
@property(nonatomic) __UIButtonCountdownDelegate *blCountdownDelegate;
@end

@implementation UIButton (Countdown)

- (void)bl_countdownWithSeconds:(int)seconds title:(NSString *(^)(int seconds))titleBlock {
    [self bl_countdownWithSeconds:seconds title:titleBlock enableWhenProcessing:NO disableWhenFinished:NO];
}

- (void)bl_countdownWithSeconds:(int)seconds
                          title:(NSString *(^)(int seconds))titleBlock
           enableWhenProcessing:(BOOL)enable
            disableWhenFinished:(BOOL)disable {
    __UIButtonCountdownDelegate *delegate = [__UIButtonCountdownDelegate new];
    delegate.button = self;
    delegate.titleBlock = titleBlock;
    delegate.enableWhenProcessing = enable;
    delegate.disableWhenFinished = disable;
    delegate.seconds = seconds;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:delegate selector:@selector(handlerTimer:) userInfo:nil repeats:YES];
    delegate.timer = timer;
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.blCountdownDelegate = delegate;
    [delegate handlerTimer:timer];
}

- (void)bl_cancelCountdown {
    __UIButtonCountdownDelegate *delegate = self.blCountdownDelegate;
    if (delegate) {
        NSTimer *timer = delegate.timer;
        if ([timer isValid]) {
            [timer invalidate];
            delegate.timer = nil;
        }
    }
    self.blCountdownDelegate = nil;
}

static char kCountdownDelKey = '\0';

- (void)setBlCountdownDelegate:(__UIButtonCountdownDelegate *)blCountdownDelegate {
    objc_setAssociatedObject(self, &kCountdownDelKey, blCountdownDelegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (__UIButtonCountdownDelegate *)blCountdownDelegate {
    return objc_getAssociatedObject(self, &kCountdownDelKey);
}

@end
